package com.xdqzy.baseline.common.utils;

import com.xdqzy.baseline.common.constant.BusiCodeEnum;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * @author dengmawei
 * @version 1.0.0
 * @ClassName IDGenarator.java
 * @Description ID或编码生成器
 * @createTime 2020年10月24日 17:36:00
 */
@Slf4j
@Component
public class IdGenarator {
    /**
     * code格式
     */
    public static final String CODE_FORMAT = "%s%d";

    /**
     * 雪花算法生成器Maps
     */
    private Map<String, SnowflakeIdWorker> snowflakeIdWorkerMaps = Maps.newHashMap();

    /**
     * 初始化
     */
    @PostConstruct
    public void init() {
        for (BusiCodeEnum busiCodeEnum : BusiCodeEnum.values()) {
            snowflakeIdWorkerMaps.put(busiCodeEnum.getBusiCodePrefix(), new SnowflakeIdWorker(1, busiCodeEnum.getBusiCode(), 0));
        }
    }

    /**
     * 生成业务编码
     * @param busiCodeEnum 业务枚举
     * @return String
     */
    public String generateCode(BusiCodeEnum busiCodeEnum) {
        return String.format(CODE_FORMAT, busiCodeEnum.getBusiCodePrefix(), snowflakeIdWorkerMaps.get(busiCodeEnum.getBusiCodePrefix()).nextId());
    }

    /**
     * @param busiCodeEnum 业务枚举
     * 生成雪花算法id ，返回long类型
     * @return long
     */
    public long generateLongId(BusiCodeEnum busiCodeEnum) {
        return new SnowflakeIdWorker(1, snowflakeIdWorkerMaps.get(busiCodeEnum.getBusiCodePrefix()).nextId(), 0).nextId();
    }
}
